package com.gsit.expenditure.component;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javafx.beans.property.BooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableCell;

//CheckBoxTableCell for creating a CheckBox in a table cell
public class CheckBoxTableCell<S, T> extends TableCell<S, T> {
	private final CheckBox checkBox;
	private ObservableValue<T> ov;
	// for test
	public static Set<Object> selectedItemSet = null;

	public CheckBoxTableCell() {
		if(selectedItemSet == null){
			selectedItemSet = new HashSet<>();
		}
		this.checkBox = new CheckBox();
		this.checkBox.setAlignment(Pos.CENTER);

		setAlignment(Pos.CENTER);
		setGraphic(checkBox);

		checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
			public void changed(ObservableValue<? extends Boolean> ov,
					Boolean old_val, Boolean new_val) {

				Object object = getTableRow().getItem();
				System.out.println("object is :: " + object);
				if (new_val) {
					boolean selected = CheckBoxTableCell.selectedItemSet.add((S) object);
					System.out
							.println("CheckBoxTableCell()--SelectedItemSet>>>>>>>>>>>>"
									+ selected);
				} else {
					if (CheckBoxTableCell.selectedItemSet.contains(object)) {
						CheckBoxTableCell.selectedItemSet.remove(object);
					}
				}

				System.out.println(" OV :: " + ov + " old val : " + old_val
						+ "  new val:: " + new_val + "index :: " + getIndex());

				// setSelectedItemSet(selectedItemSet);

			}
		});
	}

	@Override
	public void updateItem(T item, boolean empty) {
		super.updateItem(item, empty);
		System.out.println("empty is " + empty);
		if (empty) {
			setText(null);
			setGraphic(null);
		} else {
			setGraphic(checkBox);
			if (ov instanceof BooleanProperty) {
				checkBox.selectedProperty().unbindBidirectional(
						(BooleanProperty) ov);
			}
			ov = getTableColumn().getCellObservableValue(getIndex());
			if (ov instanceof BooleanProperty) {
				checkBox.selectedProperty().bindBidirectional(
						(BooleanProperty) ov);
			}
		}
	}

	public static Set<?> getSelectedItemSet() {
		return CheckBoxTableCell.selectedItemSet;
	}

	public static void setSelectedItemSet(Set<Object> selectedItemSet) {
		if(selectedItemSet == null) selectedItemSet = new HashSet<>();
		CheckBoxTableCell.selectedItemSet = selectedItemSet;
	}

}